﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using KinectGestureRecognition;
using System.Diagnostics;
using System.IO;
using System.Windows.Threading;
using System.Threading;
using WPFApp;
using CIM_Showroom.Kinect;
using Microsoft.Kinect;
using Coding4Fun.Kinect.Wpf;
using System.Drawing;


namespace CIM_Showroom
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    /// 


    public partial class MainWindow : Window
    {

        #region members
        KinectSensorModul ksm;
        private DispatcherTimer _dispatcherMouseClickTimer = new DispatcherTimer();
        private Border _focusedBorder;
        private Videoplayer _videoPlayer;
        private QR_Code _qrCode;
        private WPFApp.Window1 _slightShow;


        #region Mouse Settings
        private const float ClickThreshold = 0.33f;
        private const float SkeletonMaxX = 0.30f;
        private const float SkeletonMaxY = 0.40f;
        #endregion
      
        
        #endregion

        #region constructor
        public MainWindow()
        {
            InitializeComponent();
            ksm = KinectSensorModul.Instance;
            _dispatcherMouseClickTimer.Interval = TimeSpan.FromMilliseconds(1000);
            RegisterEvents();
            this.imageDepth.Source = ksm.ColorStreamImageProp;
            //this.imageSkeleton.Source = ksm.SkeletonFrameProp;
            //Select Mouse Cursor

            this.Cursor = Cursors.Hand;

        }

        ~MainWindow()
        {
            UnregisterEvents();
        }
        #endregion

        #region subscribe Events
        void RegisterEvents()
        {
            ksm.OnSkeletonFrameReadyEvent += new KinectSensorModul.SkeletonFrameReadyEvent(ksm_OnSkeletonFrameReadyEvent);
            //ksm.OnColorstreamReadyEvent += new KinectSensorModul.ColorStreamReadyEvent(ksm_OnColorstreamReadyEvent);
            // used for mouse coordinates
            ksm.OnGestureDetectionInterfaceEvent += new KinectSensorModul.GestureDetectionInterfaceEvent(ksm_OnGestureDetectionInterfaceEvent);
            _dispatcherMouseClickTimer.Tick += new EventHandler(_dispatcherMouseClickTimer_Tick);
        }
        #endregion

        #region Unregister Events
        void UnregisterEvents()
        {
           // ksm.OnSkeletonFrameReadyEvent -= new KinectSensorModul.SkeletonFrameReadyEvent(ksm_OnSkeletonFrameReadyEvent);
           //ksm.OnColorstreamReadyEvent -= new KinectSensorModul.ColorStreamReadyEvent(ksm_OnColorstreamReadyEvent);
            ksm.OnGestureDetectionInterfaceEvent -= new KinectSensorModul.GestureDetectionInterfaceEvent(ksm_OnGestureDetectionInterfaceEvent);
            //_dispatcherMouseClickTimer.Tick -= new EventHandler(_dispatcherMouseClickTimer_Tick);
        }
        #endregion

        #region subscribed events
        // Used for Mouse Handling
        void ksm_OnGestureDetectionInterfaceEvent(object sender, Microsoft.Kinect.Skeleton[] skeletons, long frameTimestamp)
        {
            Skeleton sd = null;
            // prevent out of range errors
            if (skeletons != null)
            {
                //get the first tracked skeleton
                sd = (from s in skeletons
                                        where s.TrackingState == SkeletonTrackingState.Tracked
                                        select s).FirstOrDefault();
            }

            if (sd == null) return;

            // make sure that the right hand is tracked
            if (sd.Joints[JointType.HandRight].TrackingState == JointTrackingState.Tracked)
            {
                int cursorX, cursorY;

                // get the left and right hand Joints
                Joint jointRight = sd.Joints[JointType.HandRight];
                Joint jointLeft = sd.Joints[JointType.HandLeft];

                // scale those Joints to the primary screen width and height
                Joint scaledRight = jointRight.ScaleTo((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.FullPrimaryScreenHeight, SkeletonMaxX, SkeletonMaxY);
                //Joint scaledLeft = jointLeft.ScaleTo((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.FullPrimaryScreenHeight, SkeletonMaxX, SkeletonMaxY);

               // Joint scaledRight = jointRight.ScaleTo((int)1800, (int)1600, SkeletonMaxX, SkeletonMaxY);
                Joint scaledLeft = jointLeft.ScaleTo((int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.FullPrimaryScreenHeight, SkeletonMaxX, SkeletonMaxY);

                {
                    cursorX = (int)scaledRight.Position.X;
                    cursorY = (int)scaledRight.Position.Y;
                }

                bool leftClick = false;
                NativeMethods.SendMouseInput(cursorX, cursorY, (int)SystemParameters.PrimaryScreenWidth, (int)SystemParameters.PrimaryScreenHeight, leftClick);

                return;
            }

        }
        void ksm_OnColorstreamReadyEvent(object sender, BitmapSource colorFrame)
        {
            if (this.imageDepth.Source == null)
            {
                imageDepth.Source = colorFrame;
            }
        }
        void ksm_OnSkeletonFrameReadyEvent(object sender, ImageSource skeletonFrame)
        {
            if (this.imageSkeleton.Source == null)
            {
                this.imageSkeleton.Source = skeletonFrame;
            }

        }
        void _dispatcherMouseClickTimer_Tick(object sender, EventArgs e)
        {

            // Simulate Mouse Click Action
            this._focusedBorder.Background = System.Windows.Media.Brushes.Green;
            _dispatcherMouseClickTimer.Stop();

            //this.UnregisterEvents();
            if (this._focusedBorder.Name.Equals("borderGame"))
            {

            }
            else if (this._focusedBorder.Name.Equals("borderPicture"))
            {
                _slightShow = new WPFApp.Window1();
                _slightShow.ShowDialog();
                _slightShow = null;
            }

            else if (this._focusedBorder.Name.Equals("borderVideo"))
            {
                _videoPlayer = new Videoplayer();
                _videoPlayer.ShowDialog();
                _videoPlayer = null;
            }

            else if (this._focusedBorder.Name.Equals("borderLeft"))
            {

            }

            else if (this._focusedBorder.Name.Equals("borderRight"))
            {

            }

            else if (this._focusedBorder.Name.Equals("borderQRCode"))
            {
                _qrCode = new QR_Code();
                _qrCode.ShowDialog();
                _qrCode = null;
            }

            //this.RegisterEvents();
        }
        #endregion

        #region help functions
        void MouseClickAbort()
        {
            this._dispatcherMouseClickTimer.Stop();
        }

        void MouseClickStart()
        {
            this._dispatcherMouseClickTimer.Start();
        }
        #endregion

        #region react 2 gui events
      
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void borderIN(object sender, MouseEventArgs e)
        {
            Debug.WriteLine("Border IN");
            this._focusedBorder = ((Border)sender);
            this._focusedBorder.BorderBrush = System.Windows.Media.Brushes.Green;
            // Activate Mouse Click Timer
            this.MouseClickStart();
        }

        private void borderOUT(object sender, MouseEventArgs e)
        {
            Debug.WriteLine("Border Out");
            this._focusedBorder = ((Border)sender);
            this._focusedBorder.BorderBrush = System.Windows.Media.Brushes.Black;
            this._focusedBorder.Background = System.Windows.Media.Brushes.Black;
            this.MouseClickAbort();
        }
        #endregion
    }
}
